<?php
/**
 *
 *
 * 替换订单时实例化
 *
 * sunjing@shopex.cn
 *
 */
class ome_order_giftreplace{
   

    public function check($order_id,$shop_id){
        $oOrderItemMdl = app::get('ome')->model('order_items');
        $orderItems = $oOrderItemMdl->db->select("SELECT sum(nums) as _num,bn,product_id,name FROM sdb_ome_order_items WHERE order_id=".$order_id." AND `delete`='false' GROUP BY bn HAVING(COUNT(bn)>1)");
        
        $bn_data = array();
        foreach($orderItems as $item){
            $rule = $this->getRule($shop_id,$item['bn'],$item['_num']);
            
            if ($rule){
                $shopdata = explode(',',$rule['shopIds']);
                
                if (in_array($shop_id,$shopdata)) {
                    $bn_data[] = $item;
                }
            }
        }
        return $bn_data;
    }

    public function getRule($shop_id,$bn,$nums){
        $time = time();
        $replaceMdl = app::get('material')->model('basic_giftreplace');
        $replaceList = $replaceMdl->db->selectrow("SELECT *  FROM sdb_material_basic_giftreplace WHERE shopIds like '%".$shop_id."%' AND material_bn='".$bn."' AND start_time<".$time." AND end_time>".$time." AND disabled='true' AND check_status='2' ORDER BY priority DESC");
       
        return $replaceList;
    }

    public function edit($order_id,$bn_data){
        //需要判断是否已经处理
        $orderObj = app::get('ome')->model('orders');
        $logObj = app::get('ome')->model('operation_log');
        $db = kernel::database();

        if ($bn_data){
            $tmp_order_object = array();
            foreach($bn_data as $bns){
                $new_data = array();
                $item_list = $db->select("SELECT * FROM sdb_ome_order_items WHERE order_id=".$order_id." AND bn='".$bns['bn']."' AND `delete`='false'");
                $price = $pmt_price=$sale_price=$amount =$nums=$divide_order_fee=$part_mjz_discount=0;
                $item_type = 'goods';
                $order_items=array();
                $item_ids = $obj_ids = array();

                foreach($item_list as $item){
                    $nums+=$item['nums'];
                    $cost+$item['cost'];
                    //$price+=$item['price'];
                    $pmt_price+=$item['pmt_price'];
                    $sale_price+=$item['sale_price'];
                    $amount+=$item['amount'];
                    $divide_order_fee+=$item['divide_order_fee'];
                    $part_mjz_discount+=$item['part_mjz_discount'];
                    $shop_goods_id = $item['shop_goods_id'];
                    $item_ids[] = $item['item_id'];
                    if ($item['sale_price']>0){
                        $obj_ids[] = $item['obj_id'];
                    }
                    
                }
                $avg_price = $amount/$nums;
                
                $object_detail = $db->selectrow("SELECT * FROM sdb_ome_order_objects WHERE order_id=".$order_id." AND obj_id in(".implode(',',$obj_ids).")");
                $order_items[] = array(
                       
                    'product_id' => $bns['product_id'],
                    'bn' => $bns['bn'],
                    'name' => $bns['name'],
                    'cost' => $object_detail['cost'] ? $object_detail['cost'] : 0.00,
                    'price' => $avg_price,
                    'pmt_price' => $pmt_price,
                    'sale_price' => $sale_price,
                    'amount' => $amount,
                    'weight' => $object_detail['weight'] ? $object_detail['weight'] : 0.00,
                    'quantity' => $nums,
                    'addon' => '',
                    'item_type' => $item_type,
                    'shop_goods_id'=>$shop_goods_id,
                    'divide_order_fee' => $divide_order_fee,
                    'part_mjz_discount' => $part_mjz_discount,
                    'is_merge'          =>  'true',

                );
                $tmp_order_object[] =array(
                    'order_id' => $order_id,
                    'obj_type' => $item_type,
                    'obj_alias' => '商品',
                    'shop_goods_id'=>$shop_goods_id,
                    'goods_id' => $object_detail['goods_id'],
                    'bn'        => $object_detail['bn'],
                    'name'      => $object_detail['name'],
                    'price'     => $avg_price,
                    'sale_price' => $sale_price,
                    'pmt_price' => $pmt_price,
                    'amount' => $amount,
                    'quantity' => $nums,
                    'order_items'=>$order_items,
                );

            }
            foreach($tmp_order_object as $ov){
                $object_detail = $db->selectrow("SELECT obj_id FROM sdb_ome_order_objects WHERE order_id=".$order_id." AND bn='".$ov['bn']."' AND quantity=".$ov['quantity']);
                if ($object_detail){
                    return false;
                }
            }
           kernel::database()->exec('begin');
           if ($tmp_order_object){
            //判断是否有同货号同数量

                $newOrder = array();
                $newOrder['order_objects'] = $tmp_order_object;
               
                $newOrder['order_id'] = $order_id;

                $rs = $orderObj->save($newOrder);
                if ($rs){
                     $db->exec("UPDATE sdb_ome_order_items SET `delete`='true' WHERE order_id=".$order_id." AND item_id in(".implode(',',$item_ids).")");

                    kernel::database()->commit();
                }else{
                    kernel::database()->rollBack();
                }
        
           
            }
            //保存快照
            $order_detail = app::get('ome')->model('orders')->dump($order_id,"*",array("order_objects"=>array("*",array("order_items"=>array("*")))));
            $logObj->write_log('order_edit@ome',$order_id,"订单赠品替换修改");
          
            $log_id = $logObj->getList('log_id',array('operation'=>'order_edit@ome','obj_id'=>$order_id),0,1,'log_id DESC');
            $log_id = $log_id[0]['log_id'];
           
            $orderObj->write_log_detail($log_id,$order_detail);
        }
        

    }
}
